package service

import (
	_ "go-web/service/redis"
	"os"
	"bufio"
	"io"
	"strings"
	"strconv"
)

var (
	FileName string
	ConfigMap map[string]string
)

func init()  {
	FileName = "config/web.properties"
	ConfigMap = make(map[string]string)

	f,err := os.Open(FileName)
	if err != nil {
		panic("读取配置文件错误")
	}
	defer f.Close()

	r := bufio.NewReader(f)
	for {
		b,_,err := r.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic("读取行数据错误")
		}

		s := strings.TrimSpace(string(b))
		if strings.Index(s, "#") == 0 {
			continue
		}

		index := strings.Index(s, "=")
		if index <= 0 {
			continue
		}

		key := strings.TrimSpace(s[:index])
		if len(key) <= 0 {
			continue
		}

		val := strings.TrimSpace(s[index+1:])
		ConfigMap[key] = val
	}
}

func Get(key string) string {
	return ConfigMap[key]
}

func GetInt(key string) (int,error)  {
	return strconv.Atoi(ConfigMap[key])
}

func GetIntDef(key string, def int) int  {
	val,err := strconv.Atoi(ConfigMap[key])
	if err != nil {
		return def
	}
	return val
}

func GetInt64Def(key string, def int64) int64  {
	val,err := strconv.Atoi(ConfigMap[key])
	if err != nil {
		return def
	}
	return int64(val)
}
